//tcp 客户端
const net = require("net");

// 数据包构建器
function buildPacket(commandClass, command, serial, data) {
  const dataBuffer = Buffer.from(data);
  const dataLength = dataBuffer.length;
  const separator = 0x2c; // 分隔符逗号','

  const parts = [
    0x3c, // 起始符 '<'
    commandClass,
    separator,
    command,
    separator,
    serial,
    separator,
    dataLength,
    separator,
    ...dataBuffer,
    separator,
    0x00, // 校验和占位
    0x3e, // 结束符 '>'
  ];

  const buffer = Buffer.from(parts);
  const checksumStart = 1;
  const checksumEnd = 9 + dataLength;
  let checksum = 0;

  for (let i = checksumStart; i <= checksumEnd; i++) {
    checksum ^= buffer[i];
  }

  buffer.writeUInt8(checksum, 10 + dataLength);
  return buffer;
}

// 数据包解析器
function parsePacket(buffer) {
  if (buffer[0] !== 0x3c || buffer[buffer.length - 1] !== 0x3e) {
    throw new Error("Invalid packet boundaries");
  }

  const dataLength = buffer[7];
  const dataStart = 9;
  const dataEnd = dataStart + dataLength;
  const expectedChecksum = buffer[buffer.length - 2];

  // 计算校验和
  let checksum = 0;
  for (let i = 1; i <= 8 + dataLength + 1; i++) {
    // 包括数据后的分隔符
    checksum ^= buffer[i];
  }

  if (checksum !== expectedChecksum) {
    throw new Error("Checksum mismatch");
  }

  return {
    commandClass: buffer[1],
    command: buffer[3],
    serial: buffer[5],
    data: buffer.slice(dataStart, dataEnd).toString(),
  };
}

const client = net.createConnection({
  host: "139.159.230.143",
  port: 81,
  // host: "localhost",
  // port: 3000,
});

client.on("connect", () => {
  console.log("连接服务器成功");
  // 发送终端注册包
  // const regData = "V3;1050;UBVJ9S12020112301;11111111111;BFEBFBFF00030679";
  // const regPacket = buildPacket(0x10, 0x10, 1, "413981618");
  // client.write(regPacket);

  // 示例：发送心跳包
  setInterval(() => {
    const heartbeat = buildPacket(0x80, 0x80, 1, "");
    client.write(heartbeat);
  }, 30000);
});

client.on("error", (err) => {
  console.error("连接错误:", err);
});

client.on("end", () => {
  console.log("我已关闭连接");
});

// 接收数据处理
const parser = new (class {
  constructor() {
    this.buffer = Buffer.alloc(0);
  }

  parse(data) {
    this.buffer = Buffer.concat([this.buffer, data]);
    const packets = [];
    while (true) {
      const start = this.buffer.indexOf(0x3c);
      if (start === -1) break;
      const end = this.buffer.indexOf(0x3e, start);
      if (end === -1) break;

      const packet = this.buffer.subarray(start, end + 1);
      this.buffer = this.buffer.subarray(end + 1);

      try {
        packets.push(parsePacket(packet));
      } catch (e) {
        console.error("解析错误:", e);
      }
    }
    return packets;
  }
})();

// 接受服务器端信息
client.on("data", (data) => {
  console.log(84, data);
  const packets = parser.parse(data);
  packets.forEach((pkt) => {
    console.log("收到数据包:", pkt);
    // 根据指令类型处理业务逻辑
  });
});
